import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

class SiwViewPage extends StatefulWidget {
  final String url;

  const SiwViewPage({super.key, required this.url});

  @override
  // ignore: library_private_types_in_public_api
  _SiwViewPageState createState() => _SiwViewPageState(url: url);
}

class _SiwViewPageState extends State<SiwViewPage> {
  final String url;
  late InAppWebViewController _webViewController;

  _SiwViewPageState({required this.url});

  // final Completer<WebViewController> _controller =
  //     Completer<WebViewController>();
  InAppWebViewSettings settings = InAppWebViewSettings(
      // isInspectable: kDebugMode,
      useOnDownloadStart: true,
      javaScriptEnabled: true,
      mediaPlaybackRequiresUserGesture: false,
      allowFileAccessFromFileURLs: true,
      allowUniversalAccessFromFileURLs: true,
      allowContentAccess: true,
      allowsAirPlayForMediaPlayback: true,
      allowsInlineMediaPlayback: true,
      iframeAllow: "camera; microphone",
      iframeAllowFullscreen: true);

  @override
  Widget build(BuildContext context) {
    // 设置状态栏颜色和文字颜色
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.white,
      statusBarIconBrightness: Brightness.dark,
    ));

    return WillPopScope(
      onWillPop: () async {
        if (await _webViewController.canGoBack()) {
          _webViewController.goBack();
          return false;
        } else {
          return true;
        }
      },
      // onPopInvoked: (didPop) async {
      //   if (await _webViewController.canGoBack()) {
      //     _webViewController.goBack();
      //   } else {}
      // },
      child: Scaffold(
        body: SafeArea(
          child: InAppWebView(
            initialUrlRequest: URLRequest(url: WebUri(url)),
            onWebViewCreated: (controller) {
              _webViewController = controller;
            },
            shouldOverrideUrlLoading: (controller, navigationAction) async {
              var url = navigationAction.request.url.toString();

              if (url.endsWith(".pdf")) {
                // 拼接 Google Drive 查看器 URL
                String pdfUrl = Uri.encodeFull(
                    "https://drive.google.com/viewerng/viewer?embedded=true&url=${url.toString()}");
                controller.loadUrl(
                    urlRequest: URLRequest(url: WebUri.uri(Uri.parse(pdfUrl))));
                return NavigationActionPolicy.CANCEL;
              }
              return NavigationActionPolicy.ALLOW;
            },
            onPermissionRequest: (controller, permissionRequest) async {
              return PermissionResponse(
                  resources: permissionRequest.resources,
                  action: PermissionResponseAction.GRANT);
            },
            // initialUrl: url,
            // javascriptMode: JavascriptMode.unrestricted,

            // onWebViewCreated: (WebViewController webViewController) {
            //   _webViewController = webViewController;
            //   _controller.complete(webViewController);
            //   _webViewController.runJavascript("setLanguage('$languageCode')");
            // },
            // onProgress: (int progress) {
            //   print("WebView is loading (progress : $progress%)");
            // },

            // navigationDelegate: (NavigationRequest request) {
            //   if (request.url.startsWith('https://www.youtube.com/')) {
            //     print('blocking navigation to $request}');
            //     return NavigationDecision.prevent;
            //   }
            //   if (request.url.endsWith('.pdf')) {
            //     print('url------- ${request.url}');
            //     final String googleDriveUrl =
            //         'https://drive.google.com/viewerng/viewer?embedded=true&url=${request.url}';
            //     _webViewController.loadUrl(googleDriveUrl);
            //     return NavigationDecision.prevent;
            //   }
            //   print('allowing navigation to $request');
            //   return NavigationDecision.navigate;
            // },
            // onPageStarted: (String url) {
            //   print('Page started loading: $url');
            // },
            // onPageFinished: (String url) {
            //   print('Page finished loading: $url');
            // },
            // gestureNavigationEnabled: false,
            // geolocationEnabled: false, //support geolocation or not
          ),
        ),
      ),
    );
  }

  // Future<void> _launchURL(String url) async {
  //   if (await canLaunchUrl(Uri.parse(url))) {
  //     await launchUrl(Uri.parse(url));
  //   } else {
  //     throw 'Could not launch $url';
  //   }
  // }
}
